import os, threading, requests, queue

from WSModule import WSModule
from WSThread import WSThread
from DafsThread import DafsThread
from WSJob import WSJob
from WSResult import WSResult
from WSOption import WSOption
from WSOptionGeneratorDict import WSOptionGeneratorDict
from WSCounter import WSCounter
from Urls import Urls
from BackupsFounderJob import BackupsFounderJob
from BackupsFounderThread import BackupsFounderThread
from Projects import Projects
from Domains import Domains

class BackupsFounder(WSModule):
    log_path = os.getcwd() + '/results/bf-result'
    options = {"threads": WSOption("threads", "Threads count, default 10", 10, False, ['-t', '--threads']),
               "project": WSOption("project", "Target project", "", True, ['-p', '--project']),
               "domain": WSOption("domain", "Target domain", "", True, ['-d', '--domain']),
               "method": WSOption("method", "Request method (default - HEAD)",
                   "HEAD", False, ['--method']),
               }
    def __init__(self, kernel): #TODO не надо вынести в WSModule?
        super().__init__(kernel)
        for option_name in self.options:
            self.options[option_name].module = self
        self.result = WSResult()

    def run(self):
        projects = Projects()
        project_id = projects.get_project_id(self.options['project'].value)
        if not project_id:
            exit(print("ERROR: Check project name or id. Project '{0}' not found.".format(self.options['project'].value)))

        domains = Domains()
        domain_id = domains.get_domain_id(project_id, self.options['domain'].value)
        if not domain_id:
            exit(print("ERROR: Check domain name or id. Domain '{0}' not found in project {1}."
                        .format(self.options['domain'].value, self.options['project'].value)))

        domain = domains.get_by_id(domain_id) #FIXME на нормальное имя исправить, может вообще в предыдущем методе всё сразу возвращать?
        urls = Urls()


        q = BackupsFounderJob()
        q.fill(urls.get_urls_by_domain_id(domain_id))

        counter = WSCounter(5, 150)

        for i in range(self.options['threads'].value):
            worker = BackupsFounderThread(q, self.result, domain['name'], self.options['method'].value, counter)
            worker.daemon = True
            worker.start()

        q.join()

    def help(self):
        return "Dafs help"

    def finished(self):
        return self.kernel.finished()
